package com.smfx.yxt.controller.sys;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.smfx.yxt.common.AdminUser;
import com.smfx.yxt.common.Constants;
import com.smfx.yxt.common.RspResult;
import com.smfx.yxt.common.enums.Status;
import com.smfx.yxt.controller.BaseController;
import com.smfx.yxt.model.SysResource;
import com.smfx.yxt.model.TeacherInfo;
import com.smfx.yxt.service.ISysResourceService;
import com.smfx.yxt.service.ITeacherService;
import com.smfx.yxt.vo.LoginReqVO;

@RequestMapping("auth")
@Controller
public class LoginController extends BaseController {
	
	private Logger logger = LoggerFactory.getLogger(LoginController.class);
	
	@Autowired
	private ITeacherService teacherService;
	@Autowired
	private ISysResourceService sysResourceService;
	
	/**
     * 根据用户角色来决定默认的展现页面.
     * @return String
     */
    @RequestMapping("login")
    public String loginPage(Model model) {
    	try {
    		AdminUser user = (AdminUser) request.getSession().getAttribute(Constants.ADMIN_USER);
        	if(user != null) {
        		return "redirect:/auth/main";
        	}
    	}catch (Exception e) {
			logger.error("loginPage exception : {}",e);
		}
    	return "auth/login";
    }
    
    @RequestMapping("loginReq")
    @ResponseBody Object loginReq(LoginReqVO vo) {
    	try {
    		TeacherInfo record = new TeacherInfo();
    		record.setIdNo(vo.getUserName());
    		record.setPassword(vo.getPassword());
    		record = teacherService.selectForWapLogin(record);
    		if(record == null) {
    			return new RspResult(Status.PWD_ERROR);
    		}
    		record.setPassword(null);
    		AdminUser adminUser = new AdminUser();
    		adminUser.setTeacherInfo(record);
    		List<SysResource> list = sysResourceService.selectMenuByIds(record.getIds());
    		adminUser.fillMenuInfo(list);
    		session.setAttribute(Constants.ADMIN_USER, adminUser);
    		return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			logger.error("---loginReq, error={}", e);
		}
    	return new RspResult(Status.FAIL);
    }
    
    @RequestMapping(value = "main", method = RequestMethod.GET)
    public String forwardToDefaultPage(Model model) {
    	model.addAttribute(Constants.ADMIN_USER, request.getSession().getAttribute(Constants.ADMIN_USER));
        return "auth/main";
    }
    
    @RequestMapping("reset")
    public String reset(Model model) {
    	session.invalidate();
    	return "redirect:/auth/login";
    }
}
